﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace Demo
{
    public class CertRequest
    {
        public void Run()
        {
            X509Certificate cert = X509Certificate.CreateFromCertFile(@"C:\Tools\OpenSSL\bin\client-2048.crt");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://identitysso.betfair.com/api/certlogin");
            request.ClientCertificates.Add(cert);
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateCheckValidationResult);
            request.ProtocolVersion = HttpVersion.Version10;
            string content = "username=zzx002&password=aaaa8888";
            request.Headers.Add("X-Application", "hobSoft");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            Stream reqStream = request.GetRequestStream();
            byte[] reqBuffer = Encoding.UTF8.GetBytes(content);
            reqStream.Write(reqBuffer, 0, reqBuffer.Length);
            reqStream.Close();

            var resTask = request.GetResponseAsync();
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(resStream, Encoding.UTF8);
                string resContent = reader.ReadToEnd();
                resStream.Close();
                response.Close();
                Console.WriteLine(resContent);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        private static bool RemoteCertificateCheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

    }
}
